package main

import (
	"fmt"
	"gitee.com/zackeus/go-boot/idgen"
	"gitee.com/zackeus/go-boot/idgen/store"
	"gitee.com/zackeus/go-boot/idgen/store/etcdstore"
	"gitee.com/zackeus/go-zero/core/logx"
	"go.etcd.io/etcd/client/pkg/v3/transport"
	clientv3 "go.etcd.io/etcd/client/v3"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	var hosts = []string{"etcd.node1.server:2379"}
	var caCertFile = "/Users/zackeus/golang/workspaces/cti/certs.d/dev/etcd/ca.pem"
	var certFile = "/Users/zackeus/golang/workspaces/cti/certs.d/dev/etcd/client-cert.pem"
	var certKeyFile = "/Users/zackeus/golang/workspaces/cti/certs.d/dev/etcd/client-key.pem"

	/* 证书 */
	tlsInfo := transport.TLSInfo{
		TrustedCAFile: caCertFile,
		CertFile:      certFile,
		KeyFile:       certKeyFile,
	}
	tlsConfig, err := tlsInfo.ClientConfig()
	if err != nil {
		logx.Error(err)
		return
	}

	/* 连接实例化 */
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   hosts,
		TLS:         tlsConfig,
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		logx.Error(err)
		return
	}
	defer func(cli *clientv3.Client) {
		_ = cli.Close()
	}(cli)

	idg, err := idgen.New(func(maxWorkerId uint16) (store.IdStore, error) {
		return etcdstore.New(cli, maxWorkerId, etcdstore.WithTTL(10), etcdstore.WithLockKey("cti/ippbx/lock/id/create"), etcdstore.WithPrefix("cti/ippbx/idgen/worker/"))
	}, idgen.WithBaseTime(1672502400000), idgen.WithWorkerIdBitLength(2), idgen.WithSeqBitLength(10))
	if err != nil {
		logx.Error(err)
		return
	}

	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	id, err := idg.NextId()
	if err != nil {
		logx.Error(err)
		return
	}
	fmt.Println("id: ", id)

	<-sig
	idg.Shutdown(true)
	time.Sleep(time.Second)
}
